﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using University.Workshop.Model;
using University.Workshop.Business;
using System.IO;
using System.Globalization;
using System.Web.Security;

namespace University.Workshop.WebApp
{
    public partial class CompareProducts : System.Web.UI.Page
    {
        private Collection<ComparedProduct> compareList;
        private int PageNumber;
        private static string AStyle = "<style> tr{color:Black} a:hover{text-decoration:underline;} a{text-decoration:none;} </style>";
        private const string colSize = "175px";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated)
                FormsAuthentication.RedirectToLoginPage();
            SetControlsInfo();
            FillData();
        }

        private void SetControlsInfo()
        {
            if (Session["selInd"] != null)
            {
                if (!IsPostBack)
                    DrpDwnSort.SelectedIndex = int.Parse(Session["selInd"] as string, CultureInfo.InvariantCulture);
            }
            if (Session["numPage"] == null)
            {
                if (!IsPostBack)
                    PageNumber = 0;
            }
            else PageNumber = int.Parse(Session["numPage"].ToString(), CultureInfo.InvariantCulture);

            compareList = new Collection<ComparedProduct>();
            Collection<long> ids = new Collection<long>();
            if (Session["compListIds"] as Collection<long> == null)
                multiView.ActiveViewIndex = 1;
            else
            {
                if ((Session["compListIds"] as Collection<long>).Count==0)
                    multiView.ActiveViewIndex = 1;
                else
                {
                    ids = Session["compListIds"] as Collection<long>;
                    multiView.ActiveViewIndex = 0;
                }
            }

            if (Request["remId"] != null)
            {
                long remId = long.Parse(Request["remId"], CultureInfo.CurrentCulture);
                if (Session["compListIds"] != null)
                {
                    ids = Session["compListIds"] as Collection<long>;
                    compareList.Clear();
                    ids = CompareProductsManager.DeleteProduct(ids, remId);
                    if (ids.Count == 0)
                        multiView.ActiveViewIndex = 1;
                }
            }
            Session["compListIds"] = ids;
            compareList = CompareProductsManager.GatherInformation(ids);

            if (PageNumber == 0)
            {
                Prev4Button.Enabled = false;
            }
            else Prev4Button.Enabled = true;
            if (PageNumber == compareList.Count / 4)
            {
                Next4Button.Enabled = false;
            }
            else Next4Button.Enabled = true;
            ShowContent.InnerText = "Showing " + ((PageNumber * 4) + 1) + "-" + ((compareList.Count > ((PageNumber + 1) * 4)) ? ((PageNumber + 1) * 4):compareList.Count) + " of " + compareList.Count + " products";
        }

        private void SetAuctionRows()
        {
            for (int ind = 0, rowPos = 8; ind < 4; ind++, rowPos++)
            {
                HtmlTableRow newRow = new HtmlTableRow();
                productsTable.Rows.Add(newRow);
                HtmlTableCell newCell = new HtmlTableCell();
                newCell.Width = "160px";
                newCell.Style.Add(HtmlTextWriterStyle.Color, "Black");
                switch (rowPos)
                {
                    case 8:
                        newCell.InnerText = "Last Bidder";
                        break;
                    case 9:
                        newCell.InnerText = "Bid Price";
                        break;
                    case 10:
                        newCell.InnerText = "Last Bid Date";
                        break;
                    case 11:
                        newCell.InnerText = "Expiration Date";
                        break;
                }
                newCell.BgColor = "#B5B5B5";
                newCell.VAlign = "top";
                productsTable.Rows[rowPos].Cells.Add(newCell);
            }
        }

        private void FillData()
        {
            int i = 0, auctions = 0;
            bool someProductInAuction = false;
            foreach (ComparedProduct item in compareList)
            {
                if (item.RelatedProduct.Status == "OnAuction")
                    auctions++;
            }
            if (auctions > 0)
                someProductInAuction = true;
            if (someProductInAuction)
            {
                SetAuctionRows();
            }

            for (int ind = (PageNumber * 4); ind < compareList.Count && ind < (PageNumber + 1) * 4; ind++)
            {
                ComparedProduct cProduct = compareList[ind];
                HtmlTableCell newCell = new HtmlTableCell();
                newCell.Width = colSize;
                newCell.InnerHtml = "<a href='CompareProducts.aspx?remId=" + cProduct.RelatedProduct.ProductId + "' >" + AStyle + "Remove Product</a>";
                productsTable.Rows[0].Cells.Add(newCell);

                newCell = new HtmlTableCell();
                newCell.Width = colSize;
                newCell.BgColor = ((i % 2 == 0) ? "#FFFFFF" : "#EEEEEE");
                newCell.VAlign = "center";
                newCell.Align = "center";
                string ImageUrl = "Thumbnails/NoImage/noimage.jpg";
                if (Directory.Exists(Server.MapPath("~/Thumbnails/") + cProduct.RelatedProduct.ProductId + "/"))
                {
                    DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/Thumbnails/") + cProduct.RelatedProduct.ProductId + "/");
                    FileInfo[] currentImages = dir.GetFiles();
                    string thumbUrl = "Thumbnails/" + cProduct.RelatedProduct.ProductId + "/";
                    if (currentImages.Length > 0)
                    {
                        ImageUrl = thumbUrl + currentImages[0].Name;
                    }
                }
                string reference = "ProductSelected.aspx?ProductID=" + cProduct.RelatedProduct.ProductId +
                    "&ProductName=" + cProduct.RelatedProduct.Name + "&ProductCategory=" + cProduct.RelatedProduct.Category;
                newCell.InnerHtml = "<table width='150' cellpadding='2' cellspacing='0'><tbody><tr><td valign='middle' align='center' height='64' bgcolor='" +
                    ((i % 2 == 0) ? "#FFFFFF" : "#EEEEEE") + "'><a href='" +
                    reference + "' > <img src='" + ImageUrl + "' border='0' alt='" + cProduct.RelatedProduct.Name + "'></a></td></tr><tr><td valign='top' align='center' bgcolor='" +
                    ((i % 2 == 0) ? "#FFFFFF" : "#EEEEEE") + "'><b><a href='" +
                    reference + "'>" + cProduct.RelatedProduct.Name + "</a></b></td></tr></tbody></table>";
                productsTable.Rows[1].Cells.Add(newCell);

                newCell = new HtmlTableCell();
                newCell.Width = colSize;
                newCell.BgColor = ((i % 2 == 0) ? "#FFFFFF" : "#EEEEEE");
                newCell.VAlign = "center";
                newCell.InnerText = cProduct.RelatedProduct.Postdate.ToShortDateString();
                productsTable.Rows[2].Cells.Add(newCell);

                newCell = new HtmlTableCell();
                newCell.Width = colSize;
                newCell.BgColor = ((i % 2 == 0) ? "#FFFFFF" : "#EEEEEE");
                newCell.VAlign = "center";
                newCell.InnerText = cProduct.RelatedProduct.Status;
                productsTable.Rows[3].Cells.Add(newCell);

                newCell = new HtmlTableCell();
                newCell.Width = colSize;
                newCell.BgColor = ((i % 2 == 0) ? "#FFFFFF" : "#EEEEEE");
                newCell.VAlign = "center";
                newCell.InnerHtml = "<a href='UserProfile.aspx?user=" + cProduct.Seller + "'>" + AStyle + cProduct.Seller + "</a>";
                productsTable.Rows[4].Cells.Add(newCell);

                newCell = new HtmlTableCell();
                newCell.Width = colSize;
                newCell.BgColor = ((i % 2 == 0) ? "#FFFFFF" : "#EEEEEE");
                newCell.VAlign = "center";
                newCell.InnerText = cProduct.RelatedProduct.Price.ToString(CultureInfo.CurrentCulture) + " " + cProduct.RelatedProduct.Currency;
                productsTable.Rows[5].Cells.Add(newCell);

                newCell = new HtmlTableCell();
                newCell.Width = colSize;
                newCell.BgColor = ((i % 2 == 0) ? "#FFFFFF" : "#EEEEEE");
                newCell.VAlign = "center";
                newCell.InnerText = cProduct.CurrentCity;
                productsTable.Rows[6].Cells.Add(newCell);

                newCell = new HtmlTableCell();
                newCell.Width = colSize;
                newCell.BgColor = ((i % 2 == 0) ? "#FFFFFF" : "#EEEEEE");
                newCell.VAlign = "center";
                newCell.InnerText = cProduct.Rate;
                productsTable.Rows[7].Cells.Add(newCell);

                if (someProductInAuction)
                {
                    SetAuctionCells(cProduct, i);
                }
                i++;
            }
        }
        private void SetAuctionCells(ComparedProduct cProduct, int i)
        {
            HtmlTableCell newCell = new HtmlTableCell();
            newCell.Width = colSize;
            newCell.BgColor = ((i % 2 == 0) ? "#FFFFFF" : "#EEEEEE");
            newCell.VAlign = "center";
            if (cProduct.LastBidder != "-")
                newCell.InnerHtml = newCell.InnerHtml = "<a href='UserProfile.aspx?user=" + cProduct.LastBidder + "'>" + AStyle + cProduct.LastBidder + "</a>";
            else newCell.InnerText = cProduct.LastBidder;
            productsTable.Rows[8].Cells.Add(newCell);

            newCell = new HtmlTableCell();
            newCell.Width = colSize;
            newCell.BgColor = ((i % 2 == 0) ? "#FFFFFF" : "#EEEEEE");
            newCell.VAlign = "center";
            newCell.InnerText = cProduct.LastBidPrice + " " + cProduct.BidCurrency;
            productsTable.Rows[9].Cells.Add(newCell);

            newCell = new HtmlTableCell();
            newCell.Width = colSize;
            newCell.BgColor = ((i % 2 == 0) ? "#FFFFFF" : "#EEEEEE");
            newCell.VAlign = "center";
            newCell.InnerText = cProduct.LastBidDate;
            productsTable.Rows[10].Cells.Add(newCell);

            newCell = new HtmlTableCell();
            newCell.Width = colSize;
            newCell.BgColor = ((i % 2 == 0) ? "#FFFFFF" : "#EEEEEE");
            newCell.VAlign = "center";
            newCell.InnerText = cProduct.AuctionExpirationDate;
            productsTable.Rows[11].Cells.Add(newCell);
        }

        protected void DrpDwnSort_SelectedIndexChanged(object sender, EventArgs e)
        {
            compareList = CompareProductsManager.SortBy(compareList, int.Parse(DrpDwnSort.SelectedValue, CultureInfo.InvariantCulture));
            Session["compListIds"] = CompareProductsManager.GetIdsList(compareList);
            Session["selInd"] = DrpDwnSort.SelectedIndex.ToString();
            Response.Redirect("CompareProducts.aspx");
        }

        protected void back_Click(object sender, EventArgs e)
        {
            Session["selInd"] = null;
            Session["numPage"] = null;
            Response.Redirect("WatchList.aspx");
        }

        protected void Next4Button_Click(object sender, EventArgs e)
        {
            Session["numPage"] = PageNumber + 1;
            Response.Redirect("CompareProducts.aspx");
        }

        protected void Prev4Button_Click(object sender, EventArgs e)
        {
            Session["numPage"] = PageNumber - 1;
            Response.Redirect("CompareProducts.aspx");
        }

        protected void btnRemoveAll_Click(object sender, EventArgs e)
        {
            Session["compListIds"] = null;
            Response.Write("<script> window.location.href = 'CompareProducts.aspx'; </script>");
        }

        protected void lnkBtnBack_Click(object sender, EventArgs e)
        {
            Session["selInd"] = null;
            Session["numPage"] = null;
        }
    }
}